package siteflash.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import java.net.URLConnection;
import java.net.URLEncoder;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;

import siteflash.data.SiteFlashPersistenceManage;
import siteflash.model.Game;
import siteflash.model.Tag;

public class General extends HttpServlet {
	public static final String BUCKETNAME = "static.y1s.org";
	
	public static ArrayList<Game> hotGames() {
		Cache cache=null;
		String cachename = "hotgames";
		ArrayList<Game> hotGames = new ArrayList<Game>();
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
        
        if (cache.containsKey(cachename)) {
        	hotGames = (ArrayList<Game>) cache.get(cachename);
        	System.out.println("Hotgame: cache print");
        } else {
			PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
	        Query query = psm.newQuery(Game.class);
	        query.setOrdering("played asc");
	        query.setRange(0, 7);
	        List<Game> listResult = (List<Game>) query.execute();
	        for (int i=0; i < listResult.size(); i++) {
	        	hotGames.add(listResult.get(i));
	        }
	        cache.put(cachename, hotGames);
	        System.out.println("Hotgame: Data print");
        }
		return hotGames;
	}
	
	public static ArrayList<Tag> getTags() {
		Cache cache=null;
		String cachename = "tags";
		ArrayList<Tag> tags = new ArrayList<Tag>();
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           e.printStackTrace();
        }
		
        if (cache.containsKey(cachename)) {
        	tags = (ArrayList<Tag>) cache.get(cachename);
        	System.out.println("Tags: cache print");
        } else {
			PersistenceManager psm = SiteFlashPersistenceManage.get().getPersistenceManager();
			Query tagQuery = psm.newQuery(Tag.class);
	        List<Tag> tagResult = (List<Tag>) tagQuery.execute();
	        Tag tag = new Tag();
	        for (int i = 0; i < tagResult.size(); i++ ) {
	        	tag = tagResult.get(i);
	        	tag.setTotal(tag.getGames().size());
	        	tag.setGames(new ArrayList<String>());
	            tags.add(tag);
	        }
	        
	        cache.put(cachename, tags);
	        System.out.println("Tags: Data print");
        }
        return tags;
	}
	
	public static int getTotal(ArrayList<Tag> tags) {
		int total = 0;
		for (int i = 0; i < tags.size(); i++ ) {
            if (tags.get(i).getName().equalsIgnoreCase("1 Player")) {
            	total = tags.get(i).getGames().size();
            }
        }
		return total;
	}
	
	public static int getFile(String urlString, String fileName) throws IOException {
		
		byte[] img = null;
		URLFetchService fetchService =
            URLFetchServiceFactory.getURLFetchService();
		// Fetch the image at the location given by the url query string parameter
		urlString = General.getURLEncode(urlString);
		URL url = new URL(urlString);
		// Fetch the image at the location given by the url query string parameter
		FetchOptions fetchOptions =FetchOptions.Builder.withDefaults();
		fetchOptions.setDeadline((double)90*60);
		HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, fetchOptions);
        HTTPResponse fetchResponse = fetchService.fetch(request);
        
        String fetchResponseContentType = null;
        for (HTTPHeader header : fetchResponse.getHeaders()) {
            // For each request header, check whether the name equals
            // "Content-Type"; if so, store the value of this header
            // in a member variable
            if (header.getName().equalsIgnoreCase("content-type")) {
                fetchResponseContentType = header.getValue();
                break;
            }
        }
        
        Boolean exists = false; //General.checkFileExists("http://" + BUCKETNAME + "/" + fileName);
        if (fetchResponseContentType != null && !exists) {
        	img = (byte[]) fetchResponse.getContent();
        	
        	FileService fileService = FileServiceFactory.getFileService();
		    GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
		       .setBucket(BUCKETNAME)
		       .setKey(fileName)
		       .setMimeType(fetchResponseContentType)
		       .setAcl("public_read").setCacheControl("public, max-age=6000");
		       
		    
		    AppEngineFile writableFile =
		        fileService.createNewGSFile(optionsBuilder.build());
		    // Open a channel to write to it
		    boolean lock = true;
		    FileWriteChannel writeChannel =
		        fileService.openWriteChannel(writableFile, lock);
		 
		    // This time we write to the channel using standard Java
		    writeChannel.write(java.nio.ByteBuffer.wrap(img));
		    // Now finalize
		    writeChannel.closeFinally();
		    System.out.println("Done writing...");
        }
        if (img == null) {
        	return 0;
        } else {
        	return img.length;
        }
        
        
	}
	
	public static String getName(String urlString) {
		String[] subStr = urlString.split("/");
		return subStr[subStr.length - 1];
	}
	
	public static ArrayList<String> getTagSeo(String message) {
		ArrayList<String> tags = new ArrayList<String>();
		try {
        	URL url = new URL("http://o2tv.vn/tag.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(500000);
			connection.setConnectTimeout(1000000);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("str="+message.replaceAll("[\\W]+", " "));
            writer.close();
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	           	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	           	 String content2 = "";
	           	 while(true)
    			 {
    				 String str = reader.readLine();
    				 if(str==null) break;
    				 content2+=str;
    			 }
	           	 Elements spans = Jsoup.parse(content2).select("body span");
	           	 if (spans.size() > 0) {
	           		 for (int i=0; i < spans.size(); i++) {
	           			 tags.add(spans.get(i).html());
	           		 }
	           	 }
            }        
        } catch (Exception e) {
			e.printStackTrace();
			System.out.println(e);
		}
		return tags;
	}
	
	public static String getUrl(String url) throws IOException {
		String content = "";
		URL dataURL = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) dataURL.openConnection();
		connection.setReadTimeout(500000);
		connection.setConnectTimeout(1000000);
		connection.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
		connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
		connection.setRequestProperty("Accept-Charset", "    ISO-8859-1,utf-8;q=0.7,*;q=0.7");
		connection.setRequestProperty("Connection", "keep-alive");
		connection.setRequestProperty("Keep-Alive", "115");
		connection.setRequestProperty("Cache-Control", "max-age=0");
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF8")));
		while (true) {
		    String str = reader.readLine();
		    if (str == null)
		        break;
		    content += str;
		}
		return content;
	}
	
	public static String getURLEncode(String url) throws IOException {
		String urlString = url.replace(" ", "%20");
		return urlString;
	}
	
	public static Boolean checkFileExists(String strUrl) throws IOException {
		URL url = new URL(strUrl);
		URLConnection connection = url.openConnection();
		Boolean exists = false;
		connection.connect();
		// Cast to a HttpURLConnection
		if ( connection instanceof HttpURLConnection)
		{
		    HttpURLConnection httpConnection = (HttpURLConnection) connection;

			int code = httpConnection.getResponseCode();
			if (code == 200 || code == 401) {
				System.out.println("File has been exists");
				exists = true;
			} else {
				exists = false;
				System.out.println("File hasn't been exists");
			}
			System.out.println(code);
		    
		}
		else
		{
		   exists = true;
		   System.out.println("error - not a http request!");
		}
		return exists;
	}
	
	public static void main(String[] args) throws IOException {
		General.checkFileExists("http://static.y1s.org/001.jpg");
	}
	
}
